﻿(function () {
    "use strict";

    var appView = Windows.UI.ViewManagement.ApplicationView;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var utils = WinJS.Utilities;

    // Vars to check if the process finished or not.
    var checkEmailFinished = true;
    var claimFinished = true;
    var registerFinished = true;

    ui.Pages.define("/pages/groupedItems/groupedItems.html", {

        // This function updates the ListView with new layouts
        initializeLayout: function (listView, viewState) {
            /// <param name="listView" value="WinJS.UI.ListView.prototype" />

            if (viewState === appViewState.snapped) {
                //console.log('initializeLayout::snapped');
                listView.itemDataSource = Data.groups.dataSource;
                listView.groupDataSource = null;
                listView.layout = new ui.ListLayout();
            } else {
                //console.log('initializeLayout::notSnapped');
                listView.itemDataSource = Data.items.dataSource;
                listView.groupDataSource = Data.groups.dataSource;
                listView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });
            }
        },

        itemInvoked: function (args) {
            if (appView.value === appViewState.snapped) {
                // If the page is snapped, the user invoked a group.
                // console.log('say groupDetail');
                var group = Data.groups.getAt(args.detail.itemIndex);
                nav.navigate("/pages/groupDetail/groupDetail.html", { groupKey: group.key });
            } else {
                // If the page is not snapped, the user invoked an item.
                // Get item from data.
                var item = Data.items.getAt(args.detail.itemIndex);

                $('.item-overlay').unbind('click').click(function (e) {
                    var itemOverlay = this;

                    // Get merchantId.                    
                    var merchantId = $(this).find(".itemId").val();

                    // Init flyout's children.
                    initFlyoutChildren(item, merchantId);

                    // Prepare flyout.
                    productFlyout.winControl.addEventListener("afterhide", function (info) {
                        clearProductFlyout();
                    });

                    // Flyout processing.checkEmail::emailExists: false
                    $("#claimButton").unbind('click').click(function () {
                        if (!checkEmailFinished) {
                            return;
                        }
                        checkEmailFinished = false;

                        // Clear password when press claim button.
                        $("#passwordEditText").val("");

                        // Get email.
                        var email = $("#emailEditText").val();

                        // Check email.
                        checkEmail(itemOverlay, email, merchantId);
                    });

                    // Show flyout.
                    productFlyout.winControl.show(itemOverlay, "right", "center");
                });

                $('.item-image').unbind('click').click(function (e) {
                    nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
                });
            }
        },

        // =================== SEMANTIC ZOOM - BEGIN ===================//
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            if (!checkInternetConnection()) {
                return;
            }

            var semanticZoom = element.querySelector("#zoom").winControl;
            var zoomedInListView = element.querySelector("#zoomedInListView").winControl;
            var zoomedOutListView = element.querySelector("#zoomedOutListView").winControl;

            zoomedOutListView.itemTemplate = element.querySelector(".zoomedOutItemTemplate");
            zoomedOutListView.itemDataSource = Data.groups.dataSource;
            zoomedOutListView.groupDataSource = null;
            zoomedOutListView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });

            zoomedInListView.groupHeaderTemplate = element.querySelector(".headerTemplate");
            zoomedInListView.itemTemplate = element.querySelector(".itemtemplate");
            zoomedInListView.oniteminvoked = this.itemInvoked.bind(this);

            if (appView.value === appViewState.snapped) {
                // If the app is snapped, configure the zoomed-in ListView
                // to show groups and lock the SemanticZoom control
                zoomedInListView.itemDataSource = Data.groups.dataSource;
                zoomedInListView.groupDataSource = null;

                zoomedInListView.layout = new ui.ListLayout();
                semanticZoom.locked = true;
            }
            else {
                // Why does it not work???? It doesn't show notFound image???
                //$(".itemImage").error(function () {
                //    console.log("ERROR");
                //    $(this).css('height', '10px');
                //    $(this).css('width', '10px');
                //    $(this).attr('src', 'http://placehold.it/300.png');
                //});

                // If the app isn't snapped, configure the zoomed-in ListView
                // to show items and groups and unlock the SemanticZoom control
                zoomedInListView.itemDataSource = Data.items.dataSource;
                zoomedInListView.groupDataSource = Data.groups.dataSource;

                zoomedInListView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });
                semanticZoom.locked = false;
            }

            //semanticZoom.element.focus(); // remove
        },

        // This function updates the page layout in response to viewState changes.
        updateLayout: function (element, viewState, lastViewState) {

            /// <param name="element" domElement="true" />
            /// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
            /// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />

            var semanticZoom = element.querySelector("#zoom").winControl;
            var zoomedInListView = element.querySelector("#zoomedInListView").winControl;

            if (appView.value === appViewState.snapped) {
                zoomedInListView.itemDataSource = Data.groups.dataSource;
                zoomedInListView.groupDataSource = null;

                zoomedInListView.layout = new ui.ListLayout();
                semanticZoom.zoomedOut = false;
                semanticZoom.locked = true;
            }
            else {
                zoomedInListView.itemDataSource = Data.items.dataSource;
                zoomedInListView.groupDataSource = Data.groups.dataSource;

                zoomedInListView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });
                semanticZoom.zoomedOut = true;
                semanticZoom.locked = false;

                // Shouldn't be necessary, but without this statement, the
                // ListView wants to scroll vertically when the app is unsnapped
                // after being snapped while zoomed out
                //nav.navigate("/pages/groupedItems/groupedItems.html"); // remove
            }
        }
        // =================== SEMANTIC ZOOM - END ===================//
    });

    /**
    ======================= CLAIM OPERATION =========================
    */
    function initFlyoutChildren(item, merchantId) {
        $("#merLogo").attr("src", item.titleImage);
        $("#merName").text(item.title);
        $("#merSMS").text(item.title);
        $("#merDiscount").text(item.description);
        $("#merAddress").text(item.address);
        $("#passwordPanel").hide();
    }

    function clearProductFlyout() {
        $("#messagePanel").text("");
        $("#merLogo").attr("src", "");
        $("#merName").text("");
        $("#merSMS").text("");
        $("#merDiscount").text("");
        $("#merAddress").text("");
        $("#passwordEditText").val("");
        $("#passwordPanel").hide();
        $("#emailEditText").val("");
    }

    function checkEmail(anchor, email, merchantId) {
        // Check empty.
        if (email == "") {
            showMessage($("#messagePanel"), "Please enter your email.");
            checkEmailFinished = true;
            return;
        }

        // Check format.
        if (!validateEmail(email)) {
            showMessage($("#messagePanel"), "Email is invalid.");
            checkEmailFinished = true;
            return;
        }

        // Check email (API #2).
        WinJS.xhr({
            url: HOST_NAME + "/checkExistEmail/?email=" + email,
            headers: {
                "Cache-Control": "no-store, no-cache, must-revalidate",
                "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT" // Remove caching previous result.
            }
        }).then(
            function onComplete(result) {
                // Check if API call is successful.
                if (result.status === 200) {
                    //console.log(result.responseText);

                    // Parse xhr to JSON.
                    var response = JSON.parse(result.response);
                    var isSuccessful = response.is_execution_successful;

                    // Check result code.
                    if (isSuccessful == true) {
                        var exist = response.data;
                        result.emailExists = exist;

                        // Return result.emailExists for the next then promise.
                        return result;
                    }
                }
            },
            function onError(error) {
                //console.log("checkEmail::error: " + error.message);
            }
        ).then(
            function onComplete(result) {
                if (result.emailExists) {
                    // Show password dialog.
                    showPasswordDialog(email, merchantId);

                } else {
                    // Prepare register form's component.
                    $("#emailEditText2").val(email).attr("readonly", "readonly");

                    // Add click handler to registerButton.
                    $("#registerButton").unbind('click').click(function () {
                        if (!registerFinished) {
                            return;
                        }
                        registerFinished = false;

                        if (validateForm()) {
                            registerAccount(merchantId);
                        }
                    });

                    // Hide claim dialog first.
                    productFlyout.winControl.hide();

                    // Show flyout.
                    registerFlyout.winControl.addEventListener("afterhide", function (info) {
                        clearRegisterFlyout();
                    });

                    registerFlyout.winControl.show(anchor, "right", "center");
                }
                return result;
            }
        ).done(
            function onComplete(result) {
                //console.log(result.responseText);
                checkEmailFinished = true;
            },

            function onError(error) {
                //console.log(error.message);
                checkEmailFinished = true;
            }
        );;
    }

    function clearRegisterFlyout() {
        $("#messagePanel2").text("");
        $("#emailEditText2").val("");
        $("#passwordEditText2").val("");
        $("#passwordConfirmEditText").val("");
    }

    function showPasswordDialog(email, merchantId) {
        // Add event handler.
        $("#okButton").unbind("click").click(function () {
            if (!claimFinished) {
                return;
            }
            claimFinished = false;

            // Get password.
            var password = $("#passwordEditText").val();

            // Redeem.
            redeemDefaultPromotion(email, password, merchantId);
        });
        $("#cancelButton").unbind("click").click(function () {
            $("#passwordPanel").fadeOut();
        });

        // Show password panel.
        $("#passwordPanel").fadeIn();
    }

    function redeemDefaultPromotion(email, password, merchantId) {
        //--kien
        var lang = "en";

        // Prepare params.
        var dataJson = { email: email, password: password, merchant_id: merchantId };

        // Redeem default promotion (API #3)
        WinJS.xhr({
            url: HOST_NAME + "/redeemDefaultPromotionViaEmail",
            type: "post",
            data: formatParams(dataJson),
            headers: {
                "Content-type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-store, no-cache, must-revalidate",
                "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
            }
        }).then(
            function onComplete(result) {
                if (result.status === 200) {
                    //console.log(result.responseText);

                    // Parse xhr to JSON.
                    var response = JSON.parse(result.response);                    
                    var isSuccessful = response.is_execution_successful;

                    // Check result code.
                    if (isSuccessful == true) {
                        // Get userId.
                        var userId = response.user_id;

                        // Do something.
                        $("#messagePanel").text("Please check your email for the redemption code.").hide().fadeIn().fadeOut(FADE_TIME);

                        // Hide password panel.
                        $("#passwordPanel").fadeOut();
                    } else {
                        var exeCode = response.execution_code;
                        if (exeCode == "FAILURE__COMMON__INVALID_PARAMS") {
                            showMessage($("#messagePanel"), "Please enter your password.");

                        } else if (exeCode == "FAILURE__PASSWORD_INVALID") {
                            showMessage($("#messagePanel"), "Password is invalid.");

                        } else if (exeCode == "FAILURE__EMAIL_INVALID") {
                            showMessage($("#messagePanel"), "Email is invalid.");

                        } else if (exeCode == "FAILURE__COMMON__USER_NOT_FOUND") {
                            showMessage($("#messagePanel"), "User is not found.");

                        } else {
                            showMessage($("#messagePanel"), "Claim failed.");
                        }
                    }
                }
                return result;
            },
            function onError(error) {
                //console.log("redeemDefaultPromotion::error: " + error.message);
            }
        ).done(
            function onComplete(result) {
                //console.log(result.responseText);
                claimFinished = true;
            },

            function onError(error) {
                //console.log(error.message);
                claimFinished = true;
            }
        );;
    }

    function showMessage(element, message) {
        element.text(message).stop(true).hide().fadeIn().fadeOut(FADE_TIME);
    }

    function validateEmail(v) {
        //var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
        //return (v.match(r) == null) ? false : true;

        //-- kien
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(v);

    }

    /**
    ======================= REGISTER OPERATION =========================
    */
    function validateForm() {
        var password = $("#passwordEditText2").val();
        var passwordConfirm = $("#passwordConfirmEditText").val();

        if (password == "") {
            showMessage($("#messagePanel2"), "Please enter your password.");
            registerFinished = true;
            return false;
        }

        if (password.length < 4) {
            showMessage($("#messagePanel2"), "The Password field must be at least 4 characters in length.");
            registerFinished = true;
            return false;
        }

        if (passwordConfirm == "") {
            showMessage($("#messagePanel2"), "Please confirm your password..");
            registerFinished = true;
            return false;
        }

        if (password != passwordConfirm) {
            showMessage($("#messagePanel2"), "Your password entries must match. Please try again.");
            registerFinished = true;
            return false;
        }

        return true;
    }

    function registerAccount(merchantId) {
        var email = $("#emailEditText2").val();
        var password = $("#passwordEditText2").val();

        //-- kien
        var lang = "en";

        // Prepare params.
        var dataJson = { email: email, password: password, merchant_id: merchantId, lang:lang };

        // Register new account and claim a merchant. (API #5)
        WinJS.xhr({
            url: HOST_NAME + "/register",
            type: "post",
            data: formatParams(dataJson),
            headers: {
                "Content-type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-store, no-cache, must-revalidate",
                "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
            }
        }).then(
            function onComplete(result) {
                // Check if API call is successful.
                if (result.status === 200) {
                    //console.log(result.responseText);

                    // Parse xhr to JSON.
                    var response = JSON.parse(result.response);
                    var isSuccessful = response.is_execution_successful;

                    // Check result code.
                    if (isSuccessful == true) {
                        var userId = response.user_id;
                        $("#messagePanel2").text("Register successful.").hide().fadeIn().fadeOut(FADE_TIME);
                        // Go to SelectTipId screen.
                        //nav.navigate("/pages/selectTipId/selectTipId.html", { userId: userId, email: email, merchantId: merchantId });
                    } else {
                        var exeCode = response.execution_code;
                        if (exeCode == "FAILURE__EMAIL_REGISTRATION__ALREADY_REGISTERED") {                            
                            showMessage($("#messagePanel2"), "This account has already been registered.");

                        } else if (exeCode == "FAILURE__EMAIL_INVALID") {
                            showMessage($("#messagePanel2"), "Email is invalid.");

                        } else if (exeCode == "FAILURE__COMMON__INVALID_PARAMS") {
                            showMessage($("#messagePanel2"), "Phone or email is null or empty.");

                        } else {
                            showMessage($("#messagePanel2"), "Register failed.");
                        }
                    }
                }
                return result;
            },
            function onError(error) {
                //console.log("registerAccount::error: " + error.message);
            }
        ).done(
            function onComplete(result) {
                //console.log(result.responseText);
                registerFinished = true;
            },

            function onError(error) {
               // console.log(error.message);
                registerFinished = true;
            }
        );

    }

})();